import Base from './base';

const request = require('request');
const crypto = require('crypto');
// const secret = ctx.config('secret'); //获取 secret 配置
function encryptSha1(data) {
  return crypto.createHash('sha1').update(data, 'utf8').digest('hex');
}
// const loginCode = //生成 authration header
export default class extends Base {
  async code2sessionAction() {
    const secret = this.config('secret'); 
    const { appid, code } = this.post();
    if (!appid || !code) this.error('接口参数错误');
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
    request(url, async (error, response, body) => {
      const json = JSON.parse(body);
      console.log(16, json);
      if (json.errcode !== 0) {
        const { openid, session_key } = json;
        const skey = encryptSha1(session_key);
        // await this.session('think', json);
        await this.cache(skey, JSON.stringify({session_key,openid}));
        await this.updateOrAddUserSession_key(openid, skey);
        this.success({ thirdSession: skey, loginCode: skey });
      } else {
        this.error(json.errmsg);
      }
    });
  }

  async updateOrAddUserSession_key(openid, session_key) {
    const model = this.model('user');
    const user = await model.where(`openid="${openid}"`).find();
    try {
      if (!think.isEmpty(user)) {
        await model.where(`openid="${openid}"`).update({ session_key });
      } else {
        await model.add({ openid, session_key });
      }
    } catch (e) {
      this.error(e.toString());
    }
  }

  async savewxuserinfoserverAction(param) {
    console.log(this.cache)
    await this.cache('1','2');
    const { userinfo, thirdSession, app_code } = this.post();
    const val = await this.cache('1');
    this.success(val);
  }
}
